<template>
  <div class="header">
      <div class="bg">
        <el-row class="top">
          <el-col :span="14">
            <span><i class="iconfont">&#xe652;</i> 客服热线：021-68810661-808</span>
            <span><i class="iconfont">&#xe651;</i> 服务时间：上午8:30--下午20:00（工作日）</span>
          </el-col>
          <el-col :span="10">
            <div class="right">
              <span @click="jumpPage('billCar.html')"><i class="iconfont">&#xe64a;</i> <a href="javascript:;">购票车 <MarkRemind v-if="isLogin" class="mes_tips" :tipsNum="this.allTips.countBillCar"/></a></span>
              <span @click="jumpPage('trade.html')"><i class="iconfont">&#xe646;</i> <a href="javascript:;">我的交易 <MarkRemind v-if="isLogin" class="mes_tips" :tipsNum="this.allTips.enterpriseOrderCount"/></a></span>
              <span class="message" @click.stop="openMsgBox">
                  <i class="iconfont">&#xe64b;</i> 
                  <a href="javascript:;">消息提醒 <MarkRemind class="mes_tips" v-if="isLogin" :tipsNum="this.msgNum"/></a>
                  <div class="message_toast" v-if="isShowMsgToast">
                      <div class="toast_inner" @click.stop="openMsgBox">
                          你有一个订单待处理，<span>点击查看 <i class="iconfont icon-gengduo1"></i></span>
                      </div>
                  </div>
                  <div class="message_box" v-if="isShowMsgBox">
                      <el-row v-for="(item,index) in waitingHandle" :key="item.id" class="message_item">
                          <el-row class="message_title">
                              <span>{{item.notification_title}}</span>
                              <span @click.stop="closeItem(index)"><i class="iconfont icon-guanbixiao"></i></span>
                          </el-row>
                          <el-row class="message_content">{{item.notification_message}}</el-row>
                          <el-row class="message_footer">
                            {{item.send_time | formatDay}}
                            <el-button type="primary" size="small" @click.stop="look(item)">
                                {{getPagePath(item.notification_type)[0].label}}</el-button>
                            </el-row>
                      </el-row>
                      <el-row class="message_operate">
                          <span @click.stop="batch_read">全部标记为已读</span>
                          <span @click.stop="moreMessage($event)">查看更多消息 <i class="iconfont icon-gengduo1"></i></span>
                      </el-row>
                  </div>
              </span>
            </div>
          </el-col>
        </el-row>
      </div>
      <el-row class="logo_base">
        <div class="logo">
            <a href="index.html"><img src="https://hpx-pc.oss-cn-beijing.aliyuncs.com/hpxpic/huipiaoxian.svg" alt="logo"></a>
        </div>
        <div class="tabs">
          <el-row class="tab">
            <div class="nav"><a :class="{active:pagePath('index.html')}" href="index.html">首页</a></div>
            <div class="nav"><a :class="{active:pagePath('market.html')}" href="market.html">企企商城</a></div>
            <div class="nav">
                <a :class="{active:pagePath('discount.html')}" href="discount.html">银行速贴<span class="hpx-red-tips">HOT</span></a>
            </div>
            <div class="nav draftTools">
                <a :class="{active:pagePath('tools.html')}" href="javascript:;">汇票助手</a>
                <el-row class="tools">
                    <transition name="el-fade-in-linear">
                        <div class="tools_panel">
                            <el-row>
                                <el-col :span="6">
                                    <a href="tools.html#/pcc" target="_blank">
                                    <dl>
                                        <dd><i class="iconfont icon-piaochacha"></i></dd>
                                        <dt>票查查</dt>
                                    </dl>
                                    </a>
                                </el-col>
                                <el-col :span="6">
                                    <a href="tools.html#/calc" target="_blank">
                                    <dl>
                                        <dd><i class="iconfont icon-jisuanqi1"></i></dd>
                                        <dt>贴现计算器</dt>
                                    </dl>
                                    </a>
                                </el-col>
                                <el-col :span="6">
                                    <a href="tools.html#/calendar" target="_blank">
                                    <dl>
                                        <dd><i class="iconfont icon-rili1"></i></dd>
                                        <dt>贴现日历</dt>
                                    </dl>
                                    </a>
                                </el-col>
                                <el-col :span="6">
                                    <a href="tools.html#/querybank" target="_blank">
                                    <dl>
                                        <dd><i class="iconfont icon-hanghaochaxun1"></i></dd>
                                        <dt>行号查询</dt>
                                    </dl>
                                    </a>
                                </el-col>
                            </el-row>
                        </div>
                    </transition>
                </el-row>
            </div>
            <div class="nav"><a href="http://www.51pjjy.com" target="_blank">票掌柜</a></div>
          </el-row>
          <!-- <transition :duration="1000" name="slide">
            <el-row class="tab-border" id="navline" :style="{'marginLeft':borderLeft + 'px'}" :class="{'hideBorder':isHideBorder}"></el-row>
          </transition> -->
        </div>
        <div class="operate">
          <el-row v-if="isLogin">
            <span class="hpx-label">
              <i class="iconfont icon-wode"></i>
              <a href="trade.html">
                <span class="enterprise_name">{{formatStr(userInfo.enterprise_name)}}</span>
                <span class="hpx-red-tips">{{userInfo.customer_name}}</span>
              </a>
            </span>
            <span class="logout" @click="logout"><i class="iconfont icon-tuichu"></i>&nbsp;退出</span>
          </el-row>
          <el-row v-if="!isLogin">
            <span class="hpx-label notLogin">
              <i class="iconfont icon-wode"></i>
              <span><a href="user.html#/login">登录</a></span> / <span @click="toRegister"><a href="javascript:;">注册</a></span>
            </span>
          </el-row>
        </div>
      </el-row>
    </div>
</template>

<script lang="ts">
  import {Vue, Component, Watch} from 'vue-property-decorator'
  import { ellipsis } from '@/util/format'
  import MarkRemind from '@component/common/MarkRemind.vue';
  import { mapGetters, mapState, mapActions } from 'vuex';
  import { Mutation, namespace } from 'vuex-class';
  import { clearInterval, setInterval } from 'timers';
  import '@/util/filter'
//   var messageStore = namespace('message')
  @Component({
        // data() {
        //   return {
        //     userInfo: {
        //       enterprise_name: '',
        //       customer_name: ''
        //     }
        //   }
        // },
        computed: {
            ...mapState([
                'messageNumber',
                'allTips'
            ]),
            ...mapGetters([
                'userInfo'
            ])
        },
        components: {
            MarkRemind
        },
        methods: {
            ...mapActions([
                'getAllTips',
                'getMessageNumber'
            ])
        }
  })
  export default class PageHeader extends Vue {
    // @messageStore.Action('getMessageNumber') getMessageNumber!:Function;
    // message = {

    // }
    timer = null
    currentPath:string = ''
    borderLeft:number = 24
    //hoverIndex = 0
    nowIndex = 0
    //是否登陆
    isLogin = false
    //页面地址集合
    pathData = [{
        path: 'index.html',
        index: 0
    },{
        path: 'market.html',
        index: 1
    },{
        path: 'discount.html',
        index: 2
    },{
        path: 'tools.html',
        index: 3
    },{
        path: 'http://www.51pjjy.com/',
        index: 4
    }]
    //待办数量
    msgNum:number = 0
    //是否显示消息通知弹框
    isShowMsgToast = false
    //是否显示待办事项下拉框
    isShowMsgBox = false
    //待办事项
    waitingHandle = []
    //消息类型
    message_type = [{
            key: 4,
            label: '去确认交易',
            path: '/seller/myBill/detail',
            baseUrl: 'bills/bill',
            ableOperateCode: 801
        },{
            key: 11,
            label: '去付款',
            path: '/buyer/order/detail',
            baseUrl: 'orders/order',
            ableOperateCode: 804
        },{
            key: 5,
            label: '去确认背书',
            path: '/seller/order/detail',
            baseUrl: 'orders/order',
            ableOperateCode: 806
        },{
            key: 12,
            label: '去确认签收',
            path: '/buyer/order/detail',
            baseUrl: 'orders/order',
            ableOperateCode: 807
    }]
//methods
    //头部跳转页面
    jumpPage (pathName:string) {
        if(this.isLogin){
            window.location.href = pathName
        }else{
            window.location.href = `user.html#/?back=${pathName}`
        }
    }
    //去注册
    toRegister () {
        if(location.href.indexOf('speedDiscount')>-1 || location.href.indexOf('discount.html')>-1){
            location.href = 'user.html#/register?back=discount.html'
        }else{
            location.href = 'user.html#/register'
        }
    }
    //退出登录
    async logout() {
      let res = await this.$http.post('customers/customerLogout')
      localStorage.removeItem('userInfo');
      localStorage.removeItem('Authorization');
      localStorage.removeItem('searchMarket');
      location.href = "user.html";
      // if(res.status == 200){
      // }
    }
    //获取实时推送消息数据
    async getPulishMsg () {
        let res = await this.$http.get('notis/notification/push', {}, { loading: false })
        if(res.status == 200 && res.data){
            this.isShowMsgToast = true
        }
        // else{
        //     this.isShowMsgToast = false
        // }
    }
    //获取消息提醒待办数目及最新三条待办
    async getUpcoming () {
        let res = await this.$http.get('notis/notification/remind')
        if(res.status == 200 && res.data){
            this.msgNum = res.data.msgCount
            this.waitingHandle = res.data.msgs
        }
    }
    //展开待办事项下拉框
    openMsgBox () {
        if(!this.isLogin){
            window.location.href = 'user.html#/?back=trade.html#/enterprise/message'
            return false
        }
        if(this.msgNum == 0){
            window.location.href = 'trade.html#/enterprise/message'
        }else{
            this.getUpcoming()
            this.isShowMsgBox = !this.isShowMsgBox
        }
        this.isShowMsgToast = false
    }
    //去操作的页面路径
    getPagePath (typeId) {
        return this.message_type.filter(item => item.key == typeId)
    }
    //
    async look (item) {
        this.isShowMsgBox = true
        //查看消息详情-将新消息置为已读
        let response = await this.$http.get(`notis/notification/${item.id}`)

        //获取目标页面的路径
        let targetPath = this.getPagePath(item.notification_type)[0].path
        //目标页面请求的url,code
        let targetUrl = this.getPagePath(item.notification_type)[0].baseUrl
        let targetCode = this.getPagePath(item.notification_type)[0].ableOperateCode
        let res = await this.$http.get(targetUrl+`/${item.notification_id}`)
        if(res.status < 300 && res.data){
            //订单状态
            if(item.notification_type == 5 || item.notification_type == 11 || item.notification_type == 12){
                if(res.data.order_status_id != targetCode || res.data.bill_status_code != targetCode){
                    this.alreadyHandle()
                    return false
                }
            }
            //票据状态
            if(item.notification_type == 4){
                if(res.data.bill_status_code != targetCode){
                    this.alreadyHandle()
                    return false
                }
            }
            window.location.href = 'trade.html#'+targetPath+`/${item.notification_id}`
        }
    }
    //待办事项已处理
    alreadyHandle () {
        this.$alert('此待办事项已处理','提示',{
            confirmButtonText: '确定',
            customClass: 'custom-message-box',
            callback: action => {
                this.getUpcoming()
                if(this.waitingHandle.length != 0){
                    this.isShowMsgBox = true
                }
            }
        })
    }
    //置为已读
    async batch_read () {
        let ids:any = []
        this.waitingHandle.map(el=>{
            ids.push(el.id)
        })
        let res = await this.$http.put('notis/notification/read',{'noticeIds':ids})
        if(res.status == 200){
            this.getUpcoming()
        }
    }
    //查看更多
    moreMessage (event) {
        // if(event) {
        //     event.stopPropagation ? event.stopPropagation(): event.cancelBubble = true;
        // }
        this.isShowMsgBox = false
        window.location.href = 'trade.html#/enterprise/message'
    }
    //关闭
    closeItem (index) {
        this.waitingHandle.splice(index,1)
        this.waitingHandle.length == 0 ? this.isShowMsgBox = false : this.isShowMsgBox = true
    }
    //格式化企业名
    formatStr (str:string) {
        return ellipsis(str,'...',8)
    }
    //
    pagePath (pageName:string) {
      return window.location.href.indexOf(pageName)>-1
    }
    @Watch('$route')
    ca(route){
        if (route.path == '/speedDiscount') {
            if (this.userInfo) {
                this.isLogin = true
                this.getAllTips()
                this.getMessageNumber()
                this.getUpcoming()
            }else{
                this.isLogin = false
            }
        }
    }
    created() {
      // let userinfo = localStorage.getItem('userInfo');
      if (this.userInfo) {
          // this.userInfo = JSON.parse(userinfo);
          this.isLogin = true
      }else{
          this.isLogin = false
      }
      this.currentPath = window.location.href
      let currentPage = this.pathData.filter(el => this.currentPath.indexOf(el.path)>-1)
      if(currentPage[0]) this.nowIndex = currentPage[0].index
      this.nowIndex != 4 ? this.borderLeft = Number(24+this.nowIndex*112) : this.borderLeft = 24;
      let body = document.querySelector('body')
      body.addEventListener('click',(e)=>{
          if(e.target.className && e.target.className != 'message') {
            this.isShowMsgBox = false
          }
      })
    }

    //
    changePage (index) {
        if(index != 3 && index != 4) this.nowIndex = index
        this.borderLeft = Number(24+index*112)
    }
    showBorder (index) {
        this.borderLeft = Number(24+index*112)
        // this.slideBar(Number(24+index*112))
    }
    restoreBorder () {
        this.borderLeft = Number(24+this.nowIndex*112)
        // this.slideBar(Number(24+this.nowIndex*112))
    }

    slideBar (fn:Number) {
        this.timer = setInterval(function(){
            let eleLeft = document.querySelector('#navline').style.marginLeft
            eleLeft = Number(eleLeft.substring(0,eleLeft.length-2))
            let speed = eleLeft > fn ? Math.floor(-fn / 5) : (eleLeft < fn ? Math.floor(fn / 5) : 0)
            let step = this.borderLeft + speed
            Vue.set(this,'borderLeft',step)
            if(this.borderLeft === fn){
                clearInterval(this.timer)
            }
        },3000)
    }
    get isHideBorder () {
        return this.currentPath.indexOf('trade.html')>-1 || this.currentPath.indexOf('stockBill.html')>-1 || this.currentPath.indexOf('user.html')>-1 || this.currentPath.indexOf('billCar.html')>-1
    }
    msgTimer:any = null
    mounted () {
        if(this.isLogin){
            this.getUpcoming()
            this.getPulishMsg()
            this.msgTimer = setInterval(()=>{this.getPulishMsg()},3000)
        }
    }
    destroyed() {
        clearInterval(this.msgTimer)
    }
  }
</script>

<style lang="scss" scoped>
    .header{
        font-size: 1.6rem;
        box-shadow: 2px 2px 10px rgba(28,31,51,.1);
        width: 100%;
        height: 96px;
        background: #fff;
        position: fixed;
        z-index: 2000;
        min-width: 1200px;
    }
    .bg{
        background: $__color-border;
    }
    .top{
        // width: 98%;
        padding: 0 40px;
        height: 36px;
        line-height: 36px;
        margin: 0 auto;
        color: $__color-show;
        font-size: 1.4rem;
        i{
            font-size: 1.5rem;
        }
        .right{
            float: right;
            // a{
            //     position: relative;
            //     .red_tips.mes_tips{
            //         position: absolute;
            //         top: 0px;
            //     }
            // }
        }
        span{
            margin-right: 4rem;
            &:last-child{
                margin: 0;
            }
        }
        .message{
            position: relative;
            .message_toast{
                position: absolute;
                z-index: 2000;
                top: 20px;
                right: 10px;
                width: 140px;
                height: 88px;
                background: url(https://hpx-pc.oss-cn-beijing.aliyuncs.com/hpxpic/msg_icon.png) no-repeat 100% 100%;
                .toast_inner{
                    width: 112px;
                    height: 40px;
                    line-height: 20px;
                    margin: 28px auto;
                    color: #fff;
                    cursor: pointer;
                    .iconfont{
                        font-size: 14px;
                    }
                }
            }
            .message_box{
                position: absolute;
                z-index: 2000;
                top: 36px;
                right: 0;
                width: 400px;
                max-height: 507px;
                padding-top: 10px;
                background: #fff;
                box-shadow:2px 2px 10px 0px rgba(28,31,51,0.2);
                border-radius: 4px;
                .message_item{
                    width: 380px;
                    height: 150px;
                    background: $__color-bg-primary;
                    border-top: 2px solid $__color-primary;
                    border-radius: 2px;
                    border-bottom-left-radius: 4px;
                    border-bottom-right-radius: 4px;
                    font-size: 14px;
                    line-height: 20px;
                    color: $__color-show;
                    padding: 10px 20px;
                    margin: 10px;
                    margin-bottom: 0;
                    &:first-child{
                        margin-top: 0;
                    }
                    .message_title{
                        font-size: 16px;
                        font-weight: 600;
                        color: $__color-label;
                        span:last-child{
                            float: right;
                            cursor: pointer;
                            .iconfont{
                                color: $__color-border;
                            }
                        }
                    }
                    .message_content{
                        margin-top: 10px;
                        height: 60px;
                        display: -webkit-box;
                        -webkit-box-orient: vertical;
                        -webkit-line-clamp: 3;
                        overflow: hidden;
                    }
                    .message_footer{
                        margin-top: 10px;
                        height: 32px;
                        line-height: 32px;
                        color: $__color-label;
                        .el-button{
                            float: right;
                        }
                    }
                }
                .message_operate{
                    padding: 0 10px;
                    span{
                        color: $__color-label;
                        cursor: pointer;
                    }
                    span:last-child{
                        float: right;
                        .iconfont{
                            font-size: 14px;
                        }
                    }
                }
            }
        }
    }
    .logo_base{
        background: #fff;
        // width: 98%;
        padding: 0 40px;
        height: 60px;
        line-height: 60px;
        margin: 0 auto;
        font-size: 1.4rem;
        position: relative;
        .logo{
            height: 60px;
            float: left;
            // margin-right: 12%;
            img{
                margin-top: 1rem;
                height: 35px;
            }
        }
        .tab-border{
            height: 3px;
            width: 64px;
            background-color: $__color-primary;
            position: absolute;
            bottom: 0;
        }
        .hideBorder{
            display: none;
        }
        .tabs{
            height: 100%;
            width: 560px;
            float: left;
            font-size: 1.6rem;
            position: absolute;
            right: 340px;
            .tab{
                // height: 57px;
                // line-height: 57px;
                .nav{
                    display: block;
                    text-align: center;
                    position: relative;
                    width: 20%;
                    float: left;
                    span{
                        position: absolute;
                        top: -1.6rem;
                        right: 25px;
                        font-size: 1.2rem;
                    }
                    a{
                        display: inline-block;
                        width: 64px;
                        &:hover{
                            color: $__color-primary;
                        }
                    }
                }
            }
        } 
        .operate{
            float: right;
            width: 300px;
            text-align: right;
            cursor: pointer;
            .hpx-label{
                margin-right: 20px;
                span{
                    text-decoration: underline;
                    cursor: pointer;
                }
                .enterprise_name{
                    margin-right: 6px;
                }
            }
			.notLogin{
				margin-right: 0;
			}
        }
    }
    .tools{
        display: none;
        position: absolute;
        z-index: 2000;
        top: 60px;
    }
    .tools_panel{
        width: 400px;
        height: 6.8rem;
        background: $__color-show;
        opacity: .9;
        font-size: 1.6rem;
        .el-row{
            height: 100%;
            .el-col{
                height: 100%;
                width: 25%;
                a{
                    display: block;
                    width: 100% !important;
                    height: 100%;
                    color: #fff;
                    dl,dd,dt{
                        margin: 0;
                        text-align: center;
                    }
                    dd{
                        height: 4rem;
                        line-height: 4rem;
                        .iconfont{
                        font-size: 2.6rem;
                        }
                    }
                    dt{
                        height: 2.2rem;
                        line-height: 2.2rem;
                    }
                    &:hover{
                        color: $__color-primary;
                    }
                }
            }
        }
    }
    .active{
        height: 56px;
        line-height: 57px;
        color: $__color-primary;
        border-bottom: 3px solid $__color-primary;
    }
    // .tab-border:hover .tools{
    //     display: block;
    // }

    .draftTools {
        position: relative;
    }

    .draftTools:hover .tools {
        display: block;
    }
</style>